package trocabi.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import trocabi.TROCABI;
import trocabi.model.Depositaire;
import trocabi.Renderer.BoldCellRenderer;
import trocabi.Renderer.ColorCellRenderer;
import trocabi.Renderer.DefaultCellRenderer;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import trocabi.Parameters;
import trocabi.Socle.JDateTextField;
import trocabi.Socle.SwingTools;
import trocabi.Socle.TechnicalException;
import static trocabi.TROCABI.ERREUR;
import static trocabi.TROCABI.fenetreExterne;
import trocabi.model.Article;
import trocabi.printer.OpenDocTools;
import trocabi.service.ArticleServices;

public class GuiFacturation extends JFrame implements ListSelectionListener {
    private static final Logger            logger = Logger.getLogger("trocabi.view.GuiFacturation");
    private Depositaire                    depositaire;
    private JTableModelFacturationArticles articlesModele;
    private ArticleServices                articlesService;
    private JTable                         jtableArticles;
    private JButton                        btRendu;
    private JButton                        btEnRecherche;
    private JButton                        btBraderie;
    private JButton                        btTerminer;
    private JButton                        btImprimerFacture;
    private JButton                        btRechercher;
    private JDateTextField                 dateDepot; // TODO: use date
    // Déclaration variables
    private static JPanel pContentPanel;
    private static JLabel lTitre;
    private static JPanel pCenter;
    private static JLabel lIdentification;
    private static JPanel pRecherche;
    private static JPanel pBoutons1;
    private static JScrollPane spListe;

    private static JPanel pBoutons2;

    public GuiFacturation() {
        initComponents();
    }
    
    private void initComponents() {
        this.setTitle("Facturation : État des ventes");
        this.setSize(530, 500);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        // Content panel de type BorderPanel --> nord = titre / centre = contenu / sud = licence, droits, auteurs ...
        pContentPanel = new JPanel(new BorderLayout());
        pContentPanel.setBackground(Color.white);
        this.setContentPane(pContentPanel);

        // Titre
        lTitre = new JLabel("<html><body><br />Facturation :<br /><br /></body></html>");
        lTitre.setHorizontalAlignment(SwingConstants.CENTER);
        pContentPanel.add(lTitre, BorderLayout.NORTH);

        /*
         * Que du gridBagLayout
         * Panel de 5 lignes --> lignes 2 à 5 contiennent des panels (ligne 4 = scrollpanel / les autres = GridBagLayout)
         */
        pCenter = new JPanel(new GridBagLayout());
        GridBagConstraints tmp = new GridBagConstraints();
        // Label Nom, Prénom, ID
        lIdentification = new JLabel("<Nom> <Prénom> <Identifiant>");
        tmp.gridx = 0;
        tmp.gridy = 0;
        tmp.insets = new Insets(10, 10, 0, 10);
        tmp.fill = GridBagConstraints.HORIZONTAL;
        tmp.anchor = GridBagConstraints.LINE_START;
        pCenter.add(lIdentification, tmp);
        // Recherche
        pRecherche = new JPanel(new GridBagLayout());
        tmp.gridx = 0;
        tmp.gridy = 0;
        tmp.fill = GridBagConstraints.NONE;
        pRecherche.add(new JLabel("Date de dépôt :"), tmp);
         try {
            dateDepot = new JDateTextField(Parameters.FORMAT_DATE); // date par defaut
        } catch (ParseException ex) {
            Logger.getLogger(GuiInventaire.class.getName()).log(Level.SEVERE, null, ex);
        }
        dateDepot.setColumns(10);
        dateDepot.setPreferredSize(new Dimension(100, 20));
        tmp.gridx = 1;
        pRecherche.add(dateDepot, tmp);
        btRechercher = new JButton("Rechercher");
        btRechercher.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                chercherArticle(dateDepot.getDate());
            }
        });
        tmp.gridx = 2;
        tmp.weightx = 1;
        tmp.anchor = GridBagConstraints.LINE_START;
        pRecherche.add(btRechercher, tmp);
        tmp.gridx = 0;
        tmp.gridy = 1;
        tmp.weightx = 0;
        tmp.fill = GridBagConstraints.HORIZONTAL;
        pCenter.add(pRecherche, tmp);
        // Sous-panel "Rechercher Dépositaire"
        pBoutons1 = new JPanel(new GridBagLayout());
        btRendu = new JButton("\"Rendu\"");
        btRendu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changerEtatArticle(Article.Etat.RENDU);
            }
        });
        tmp.gridx = 0;
        tmp.gridy = 0;
        tmp.fill = GridBagConstraints.NONE;
        pBoutons1.add(btRendu, tmp);
        btEnRecherche = new JButton("\"En recherche\"");
        btEnRecherche.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changerEtatArticle(Article.Etat.EN_RECHERCHE);
            }
        });
        tmp.gridx = 1;
        pBoutons1.add(btEnRecherche, tmp);
        btBraderie = new JButton("\"Braderie\"");
        btBraderie.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changerEtatArticle(Article.Etat.BRADERIE);
            }
        });
        tmp.gridx = 2;
        tmp.weightx = 1;
        tmp.anchor = GridBagConstraints.LINE_START;
        pBoutons1.add(btBraderie, tmp);
        tmp.gridx = 0;
        tmp.gridy = 2;
        tmp.fill = GridBagConstraints.BOTH;
        pCenter.add(pBoutons1, tmp);
        // Sous-panel "Afficher Résultats Recherche"
        articlesModele = new JTableModelFacturationArticles(); 
        articlesModele.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent tme) {
                if (articlesModele.getRowCount() > 0) {
                    btImprimerFacture.setEnabled(true);
                } else {
                    btImprimerFacture.setEnabled(false);
                }
            }
        });
        jtableArticles = new JTable(articlesModele);
        int[] colSize = { 85, 100, 70, 170, 80, 80, 80, 70, 70 };
        SwingTools.setJTableSize(jtableArticles, colSize);
      
        jtableArticles.setDefaultRenderer(Object.class, new DefaultCellRenderer());
        jtableArticles.getColumnModel().getColumn(0).setCellRenderer(new BoldCellRenderer());
        jtableArticles.getColumnModel().getColumn(8).setCellRenderer(new ColorCellRenderer());
        jtableArticles.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jtableArticles.getSelectionModel().addListSelectionListener(this);
        TableRowSorter<TableModel> rsSorter = new <TableModel>TableRowSorter(jtableArticles.getModel());
        jtableArticles.setRowSorter(rsSorter);
        rsSorter.setSortsOnUpdates(true);
        spListe = new JScrollPane(jtableArticles);
        tmp.gridx = 0;
        tmp.gridy = 3;
        tmp.weightx = 0;
        tmp.weighty = 1;
        pCenter.add(spListe, tmp);
        // Sous-panel "Boutons"
        pBoutons2 = new JPanel(new GridBagLayout());
        btImprimerFacture = new JButton("Imprimer une facture");
        btImprimerFacture.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ArrayList<Article> articlesPayes=new ArrayList<>();
                OpenDocTools odt=OpenDocTools.getInstance();
                for (Article article: articlesModele.getArticles()) {
                    if (article.getSituation().equals("VENDU")) {
                        articlesPayes.add(article);
                    }
                }
                odt.facture_depositaire(articlesPayes, depositaire);
            }
        });
        tmp.gridx = 0;
        tmp.gridy = 0;
        tmp.insets = new Insets(10, 10, 10, 10);
        tmp.weighty = 0;
        tmp.fill = GridBagConstraints.NONE;
        tmp.anchor = GridBagConstraints.LINE_START;
        pBoutons2.add(btImprimerFacture, tmp);
        btTerminer = new JButton("Terminer");
        btTerminer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        tmp.gridx = 1;
        tmp.weightx = 1;
        tmp.anchor = GridBagConstraints.LINE_END;
        pBoutons2.add(btTerminer, tmp);
        tmp.gridx = 0;
        tmp.gridy = 4;
        tmp.fill = GridBagConstraints.HORIZONTAL;
        pCenter.add(pBoutons2, tmp);
        pContentPanel.add(pCenter, BorderLayout.CENTER);
    }

    public void setDefault() {
        this.setLocationRelativeTo(null);
        dateDepot.setText("");
        btRendu.setEnabled(false);
        btEnRecherche.setEnabled(false);
        btBraderie.setEnabled(false);
        btImprimerFacture.setEnabled(false);
        articlesModele.removeAll();
    }

    public void setDepositaire(Depositaire dpDepositaire_tmp) {
        depositaire = dpDepositaire_tmp;
        setDefault();
        lIdentification.setText(TROCABI.formatageString(depositaire.getNom()) + " " + TROCABI.formatageString(depositaire.getPrenom()) + " N° Identifiant : " + depositaire.getId());
    }


    @Override
    public void valueChanged(ListSelectionEvent lse) {
        if (lse.getSource() == jtableArticles.getSelectionModel()) {
            if (jtableArticles.getSelectedRowCount() >= 1) {
                btRendu.setEnabled(true);
                btEnRecherche.setEnabled(true);
                btBraderie.setEnabled(true);
            } else {
                btRendu.setEnabled(false);
                btEnRecherche.setEnabled(false);
                btBraderie.setEnabled(false);
            }
        } else {
            TROCABI.fenetreExterne(TROCABI.ERREUR, "Erreur inattendue : source de l'évènement inconnue");
        }
    }
    
    public void chercherArticle(java.util.Date dtDateDepot) {
        ArrayList<Article> articles;
        try {
            articles = articlesService.searchUntilDateDepot(depositaire, dtDateDepot);
        } catch (TechnicalException ex) {
            fenetreExterne(ERREUR, "Erreur inattendue lors de la sélection des articles.");
            return;
        }
        articlesModele.add(articles);
    }

     void changerEtatArticle(Article.Etat etat) {
        int[] iSelectedRows = jtableArticles.getSelectedRows();
        try {
            for (int i = 0; i < iSelectedRows.length; i++) {
                Article article = articlesModele.getArticleAt(iSelectedRows[i]);
                articlesService.changeState(article, etat);
            }      
        } catch (TechnicalException e) {
            logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
            fenetreExterne(ERREUR, String.format("Erreur inattendue lors de la mise à jour de l'article %s",e.getMessage()));
        }
        articlesModele.refresh();
    }
}
